#include "basic_time.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum {
	TIME_YEAR, TIME_MONTH, TIME_DAY, TIME_HOUR, TIME_MINUTE, TIME_SECOND
} e_BasicTime;

static int GetFormatTime(const char *strTime, const char *strFmt, e_BasicTime type, char *value) {
	char *format = strdup(strFmt);
	char *expression = (char *)malloc(strlen(strFmt)+256);
	char *ptype = NULL;
	char *percent = NULL;
	char *nextPercent = NULL;
	int intervalPos = 0;
	int getRet = -1;

	switch (type) {
		case TIME_YEAR: ptype = strstr(format, "%Y"); break;
		case TIME_MONTH: ptype = strstr(format, "%m"); break;
		case TIME_DAY: ptype = strstr(format, "%d"); break;
		case TIME_HOUR: ptype = strstr(format, "%H"); break;
		case TIME_MINUTE: ptype = strstr(format, "%M"); break;
		case TIME_SECOND: ptype = strstr(format, "%S"); break;
		default: break;
	}
	if (NULL != ptype) {
		*(ptype+2) = 0;

		strcpy(expression, "");
		percent = strpbrk(format, "%%");
		nextPercent = strpbrk(percent+1, "%%");
		while (NULL != nextPercent) {
			intervalPos = nextPercent - percent;
			if (2 < intervalPos) {
				if ('Y' == *(percent+1))
					strcat(expression, "%*4[0-9]%*[^0-9]");
				else 
					strcat(expression, "%*2[0-9]%*[^0-9]");
			}
			else {
				if ('Y' == *(percent+1))
					strcat(expression, "%*4[0-9]");
				else 
					strcat(expression, "%*2[0-9]");
			}
			percent = nextPercent;
			nextPercent = strpbrk(percent+1, "%%");
		}
		if (TIME_YEAR == type) 
			strcat(expression, "%4[0-9]"); 
		else
			strcat(expression, "%2[0-9]");
		sscanf(strTime, expression, value);
		getRet = 0;
	}

	free(format);
	free(expression);
	return getRet;
}

char* strptime(const char *strTime, const char *strFmt, struct tm *tmTime) {
	char year[8] = {0}, month[8] = {0}, day[8] = {0};
	char hour[8] = {0}, minute[8] = {0}, second[8] = {0};
	struct tm tm;

	GetFormatTime(strTime, strFmt, TIME_YEAR, year);
	GetFormatTime(strTime, strFmt, TIME_MONTH, month);
	GetFormatTime(strTime, strFmt, TIME_DAY, day);
	GetFormatTime(strTime, strFmt, TIME_HOUR, hour);
	GetFormatTime(strTime, strFmt, TIME_MINUTE, minute);
	GetFormatTime(strTime, strFmt, TIME_SECOND, second);
	//printf("%s\n%s\n", strTime, strFmt);
	//printf("%s %s %s %s %s %s\n", year, month, day, hour, minute, second);

	memset(&tm, 0, sizeof(struct tm));
	tm.tm_year = atoi(year) - 1900;
	tm.tm_mon = atoi(month) - 1;
	tm.tm_mday = atoi(day);
	tm.tm_hour = atoi(hour);
	tm.tm_min = atoi(minute);
	tm.tm_sec = atoi(second);
	memcpy(tmTime, &tm, sizeof(struct tm));

	return (char *)(strTime+strlen(strTime));
}


#if 0
int main(void) {
	struct tm tm;
	time_t rawtime;
	char buf[256];

	//strptime("1989-10-22 11:23:45", "%Y-%m-%d %H:%M:%S", &tm);
	//strptime("19891022 11:23:45", "%Y%m%d %H:%M:%S", &tm);
	//strptime("19891022112345", "%Y%m%d%H%M%S", &tm);
	strptime("11234519891022", "%H%M%S%Y%m%d", &tm);
	rawtime = mktime(&tm);
	
	strftime(buf, sizeof(buf), "%H:%M:%S %Y/%m/%d", &tm);
	puts(buf);

	return 0;
}
#endif

